<template>
  <view class="page">
    <view v-if="!order._id" class="loading">
      <view style="text-align: center; padding: 100rpx 32rpx;">
        <view style="font-size: 28rpx; color: #999;">加载中...</view>
      </view>
    </view>
    <view v-else class="purchase-list">
      <!-- 订单信息 -->
      <view class="order-header">
        <view class="order-no">订单号: {{ order.order_no }}</view>
        <view class="order-time">{{ formatTime(order.create_date) }}</view>
      </view>

      <!-- 菜品材料分类 -->
      <view v-for="dish in order.dishes" :key="dish.id" class="dish-section">
        <view class="dish-header">
          <view class="dish-name">{{ dish.name }}</view>
          <view class="dish-qty">× {{ dish.count }}</view>
        </view>

        <!-- 主材 -->
        <view v-if="dish.mainMaterials && dish.mainMaterials.length > 0" class="material-group">
          <view class="material-type">主材</view>
          <view v-for="(material, idx) in dish.mainMaterials" :key="`main-${idx}`" class="material-item">
            <view class="material-name">{{ material }}</view>
            <view class="material-qty">× {{ dish.count }}</view>
          </view>
        </view>

        <!-- 辅材 -->
        <view v-if="dish.secondaryMaterials && dish.secondaryMaterials.length > 0" class="material-group">
          <view class="material-type">辅材</view>
          <view v-for="(material, idx) in dish.secondaryMaterials" :key="`secondary-${idx}`" class="material-item">
            <view class="material-name">{{ material }}</view>
            <view class="material-qty">× {{ dish.count }}</view>
          </view>
        </view>

        <!-- 调味品 -->
        <view v-if="dish.seasonings && dish.seasonings.length > 0" class="material-group">
          <view class="material-type">调味品</view>
          <view v-for="(material, idx) in dish.seasonings" :key="`seasoning-${idx}`" class="material-item">
            <view class="material-name">{{ material }}</view>
            <view class="material-qty">× {{ dish.count }}</view>
          </view>
        </view>

        <!-- 无材料提示 -->
        <view v-if="!hasMaterials(dish)" class="no-materials">
          暂无材料信息
        </view>
      </view>

      <!-- 返回按钮 -->
      <view class="footer">
        <button 
          size="default"
          type="default"
          class="btn-back"
          style="background-color: #e5e7eb; color: #374151; border-color: #e5e7eb;"
          hover-class="btn-back-hover"
          @click="goBack"
        >
          返回
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const order = ref({
  _id: '',
  order_no: '',
  dishes: [],
  create_date: null
})

function formatTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

function hasMaterials(dish) {
  return (dish.mainMaterials?.length > 0) || 
         (dish.secondaryMaterials?.length > 0) || 
         (dish.seasonings?.length > 0)
}

async function loadOrderDetail(orderId) {
  uni.showLoading({ mask: true })
  try {
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: {
        action: 'get-order-detail',
        data: {
          order_id: orderId
        }
      }
    })

    if (res.result && res.result.code === 200) {
      order.value = res.result.data
      
      // 获取所有菜品的材料信息
      const dishIds = order.value.dishes.map(d => d.id)
      if (dishIds.length > 0) {
        const materialsRes = await uniCloud.callFunction({
          name: 'food-dishes',
          data: {
            action: 'get-dish-materials',
            data: {
              dishIds: dishIds
            }
          }
        })
        
        if (materialsRes.result && materialsRes.result.code === 200) {
          const materialsMap = materialsRes.result.data
          
          // 将材料信息合并到订单菜品中
          order.value.dishes = order.value.dishes.map(dish => {
            const materials = materialsMap[dish.id] || {}
            const ingredients = materials.ingredients || {}
            
            return {
              ...dish,
              mainMaterials: ingredients.main_ingredients ? ingredients.main_ingredients.split('，') : [],
              secondaryMaterials: ingredients.auxiliary_ingredients ? ingredients.auxiliary_ingredients.split('，') : [],
              seasonings: ingredients.seasonings ? ingredients.seasonings.split('，') : []
            }
          })
        }
      }
    } else {
      uni.showToast({
        title: res.result?.message || '加载失败',
        icon: 'none'
      })
    }
  } catch (err) {
    console.error('加载订单详情出错:', err)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

function goBack() {
  uni.navigateBack()
}

onLoad((options) => {
  if (options.orderId) {
    loadOrderDetail(options.orderId)
  }
})
</script>

<style lang="scss" scoped>
$primary-color: #10b981;

.page {
  min-height: 100vh;
  background: #f8fafc;
  padding: 20rpx;
  padding-bottom: 100rpx;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.purchase-list {
  .order-header {
    background: #fff;
    padding: 16rpx;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.06);

    .order-no {
      font-size: 28rpx;
      font-weight: 600;
      color: #0f172a;
      margin-bottom: 8rpx;
    }

    .order-time {
      font-size: 24rpx;
      color: #6b7280;
    }
  }

  .dish-section {
    background: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.06);

    .dish-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16rpx;
      background: linear-gradient(135deg, $primary-color, #059669);
      color: #fff;
      border-bottom: 1rpx solid #e5e7eb;

      .dish-name {
        font-size: 28rpx;
        font-weight: 600;
      }

      .dish-qty {
        font-size: 24rpx;
      }
    }

    .no-materials {
      padding: 20rpx 16rpx;
      text-align: center;
      color: #9ca3af;
      font-size: 24rpx;
    }

    .material-group {
      padding: 16rpx;
      border-bottom: 1rpx solid #f3f4f6;

      &:last-child {
        border-bottom: none;
      }

      .material-type {
        font-size: 24rpx;
        font-weight: 600;
        color: $primary-color;
        margin-bottom: 12rpx;
        padding-bottom: 8rpx;
        border-bottom: 1rpx dashed $primary-color;
      }

      .material-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10rpx 0;
        font-size: 24rpx;
        color: #1f2937;

        .material-name {
          flex: 1;
        }

        .material-qty {
          color: $primary-color;
          font-weight: 600;
          margin-left: 12rpx;
        }
      }
    }
  }

  .footer {
    display: flex;
    gap: 12rpx;
    padding: 20rpx 0;

    .btn-back {
      flex: 1;
      height: 44rpx;
      border-radius: 10rpx;
      font-size: 28rpx;
      font-weight: 600;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
    }

    .btn-back-hover {
      background-color: #d1d5db !important;
      color: #1f2937 !important;
    }
  }
}
</style>
